/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2011
 */


#include "popup.h"
#include <QtGui/QTextBrowser>
#include <QtGui/QToolBar>
#include <QtGui/QAction>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMouseEvent>
#include <QtGui/QKeyEvent>
#include <QApplication>


Popup::Popup(QWidget *parent) :
    resultText(new QTextBrowser(this)),
    toolBar(new QToolBar(this)),
    pronounceAction(new QAction(this)),
    QFrame(parent, Qt::Popup),
    m_clipboard(QApplication::clipboard())
{




    this->setMouseTracking(true);
    this->setFrameShape(QFrame::StyledPanel);
    this->setFrameShadow(QFrame::Raised);
//    this->setFrameStyle( QFrame::Sunken);
    this->setLineWidth(0);

    QVBoxLayout *mainLayout = new QVBoxLayout;
//    mainLayout->addWidget(toolBar);
    mainLayout->addWidget(resultText);
    mainLayout->setContentsMargins(0,0,0,0);
    resultText->setFrameShape(QFrame::NoFrame);
    this->setLayout(mainLayout);



    m_timer.setSingleShot(true);
    connect(&m_timer, SIGNAL(timeout()),this, SLOT(timeoutHandler()));
    connect(m_clipboard, SIGNAL(selectionChanged()), this, SLOT(updateCursorPos()));
}

Popup::~Popup() {
    delete resultText;
    delete toolBar;
    delete pronounceAction;
}

void Popup::popup(const QString &text) {
    this->popup(m_cursor_pos, text);
}


void Popup::popup(const QPoint &pos, const QString &text) {
    this->move(pos);
    this->setWindowFlags(Qt::Popup);
    resultText->setPlainText(text);
    this->show();
}


void Popup::setShowToolbar(bool flag) {
    toolBar->setHidden(!flag);
}

//void Popup::setTextFont(const QFont &font) {
//    resultText->setFont(font);
//}

void Popup::updateCursorPos() {
    if(!m_pos_locked)
        m_cursor_pos = QCursor::pos();
}

void Popup::mouseReleaseEvent(QMouseEvent *e) {
    hide();
    e->accept();
}


void Popup::keyReleaseEvent(QKeyEvent *e) {

}

void Popup::leaveEvent(QEvent *e) {

}

void Popup::timeoutHandler() {
    if(m_timer.interval() > 0) this->hide();
}
